﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Definition of a property which can be assigned a nullable value.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class NullablePropertyDefinition<T> : PropertyDefinition<T?>
		where T : struct
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="shortName"></param>
		/// <param name="defaultValue"></param>
		public NullablePropertyDefinition(string name, string shortName, T? defaultValue)
			: base(name, shortName, defaultValue)
		{
		}
		#endregion
		#region EVENTS
		#endregion
		#region PROPS
		#endregion
		#region METHODS
		/// <summary>
		/// Deserializes the value of this property from the specified <see cref="JsonReader"/>.
		/// </summary>
		/// <param name="control"></param>
		/// <param name="jr"></param>
		public override void DeserializeValue(TControl control, TA.JSON.JsonReader jr)
		{
			T? t = null;
			if (jr.TokenType != TA.JSON.JsonToken.Null)
			{
				try
				{
					t = (T)jr.Value;
				}
				catch
				{
					try
					{
						t = (T)Convert.ChangeType(jr.Value, typeof(T));
					}
					catch
					{
						throw new Exception("Failed to deserialize value for property " + this.Name);
					}
				}
			}
			this.SetValue(control, t);
		}
		#endregion
		#endregion
		#region INTERNAL
		#region CONST/STATIC
		#endregion
		#region VARS
		#endregion
		#region PROPS
		#endregion
		#region METHODS
		#region INIT
		#endregion
		#region DATA
		#endregion
		#region HANDLERS
		#endregion
		#endregion
		#endregion				
				
	}
}
